package com.example.project.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;

import com.example.project.HomeActivity;
import com.example.project.utils.JsonParser;
import com.example.project.utils.StringUtils;

import android.app.IntentService;
import android.content.Intent;

public class LoginService extends IntentService {

	public LoginService() {
		super("LoginService");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		String address = intent.getStringExtra("address");
		String port = intent.getStringExtra("port");
		String username = intent.getStringExtra("username");
		String password = intent.getStringExtra("password");
		String uri = new StringBuffer("http://").append(address).append(':').append(port).append("/connect").toString();
		
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpPost httpPost = new HttpPost(uri);
		
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("username", username));
			nameValuePairs.add(new BasicNameValuePair("password", password));
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			
			HttpResponse response = httpClient.execute(httpPost, localContext);
			HttpEntity entity = response.getEntity();
			
			String responseStr = StringUtils.inputStreamToString(entity.getContent());
			
			Intent homeIntent = new Intent(getBaseContext(), HomeActivity.class);
			homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			homeIntent.putExtra("address", address);
			homeIntent.putExtra("port", port);
			JsonParser.parseConnectResponse(homeIntent, responseStr);
			
			getApplication().startActivity(homeIntent);

		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

}
